<template>
  <!-- 企业管理 -->
  <div class="box">
    <div class="body">
      <!-- 搜索框 -->
      <el-form ref="form" class="formone" :model="form" label-width="80px">
        <el-form-item label="标签名称">
          <el-input v-model="form.tags" />
        </el-form-item>
        <el-form-item label="城市">
          <el-select v-model="form.province" placeholder="请选择城市">
            <el-option
              v-for="item in provinceArry"
              :key="item.code"
              :label="item.name"
              :value="item.name"
              @click.native="provinceFn(item.code)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地区">
          <el-select v-model="form.city" placeholder="请选择地区">
            <el-option
              v-for="item in cityArry"
              :key="item.code"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业简称">
          <el-input v-model="form.shortName" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.state" placeholder="请选择状态">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="clearFn">清除</el-button>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-button icon="el-icon-edit" type="success" @click="addUserFn">
        新增用户
      </el-button>
      <el-alert type="info" :closable="false" class="incoTitle">
        <i class="el-icon-info" style="font-size: 16px" /> 共 {{ total }} 条记录
      </el-alert>

      <!-- 列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          :index="indexFn"
          width="100"
        />
        <el-table-column prop="number" label="企业编号" width="160" />
        <el-table-column prop="shortName" label="企业简称" width="120" />
        <el-table-column prop="tags" label="标签" width="100" />
        <el-table-column prop="creatorID" label="创建者" width="100" />
        <el-table-column prop="addDate" label="创建日期" width="160">
          <template #default="{ row }">
            {{ row.addDate | timefilter('YYYY-MM-DD  HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="160" />
        <el-table-column
          prop="state"
          label="状态"
          :formatter="formatterFn"
          width="100"
        />
        <el-table-column prop="" label="操作" width="160">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              plain
              circle
              @click="editFn(row.id)"
            />
            <el-tooltip
              class="item"
              effect="dark"
              :content="row.state === 1 ? '禁用' : '启用'"
              placement="top"
            >
              <el-button
                v-if="row.state === 1"
                type="warning"
                icon="el-icon-close"
                circle
                plain
                @click="forbiddenFn(row.id, 0)"
              />
              <el-button
                v-else
                type="primary"
                icon="el-icon-check"
                circle
                plain
                @click="forbiddenFn(row.id, 1)"
              />
            </el-tooltip>

            <el-button
              type="danger"
              icon="el-icon-delete"
              plain
              circle
              @click="delFn(row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 弹窗  -->
    <el-dialog
      :title="showTitle"
      :visible.sync="dialogVisible"
      :before-close="cancel"
    >
      <el-form
        ref="dataform"
        class="popform"
        :model="dataform"
        label-width="140px"
        :rules="poprules"
      >
        <el-form-item label="企业名称" prop="shortName">
          <el-input v-model="dataform.shortName" />
        </el-form-item>
        <el-form-item label="所属公司" prop="company">
          <el-input v-model="dataform.company" />
        </el-form-item>
        <div class="annotation">
          https://www.tianyancha.com （在此可查询所属公司全称及简称）
        </div>
        <el-form-item label="城市地区" prop="province">
          <el-select v-model="dataform.province" placeholder="请选择">
            <el-option
              v-for="item in provinceArry"
              :key="item.code"
              :label="item.name"
              :value="item.name"
              @click.native="provinceFn(item.code)"
            />
          </el-select>
          <el-select v-model="dataform.city" placeholder="请选择">
            <el-option
              v-for="item in cityArry"
              :key="item.code"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="方向（企业标签）" prop="tags">
          <el-input v-model="dataform.tags" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="dataform.remarks" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="subeditFn"> 确 定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { ChineseDistricts } from '@/utils/area'
import {
  getBusAdminApi,
  editStateApi,
  getBusAdminDetailsApi,
  delUserApi,
  getFirmApi,
  editBusAdminApi,
  addBusAdminApi
} from '@/api/businessAdmin'
export default {
  data() {
    return {
      form: {
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: ''
      },
      provinceArry: [], // 城市数组
      cityArry: [], // 地区数组
      // content: '', // 列表右侧操作提示禁用or启用
      tableData: [], // 企业管理列表
      id: '', // 当前企业
      // dataobj: {}, // 企业管理详情
      // 分页
      total: 0, // 总条数
      page: 1,
      pagesize: 10,
      // 弹窗
      dialogVisible: false, // 弹窗状态
      dataform: {
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: '',
        isFamous: true
      },
      // 弹窗校验
      poprules: {
        shortName: [
          {
            required: true,
            message: '企业名称不能为空',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 10,
            message: '在1-10字符之间',
            trigger: ['blur', 'change']
          }
        ],
        company: [
          {
            required: true,
            message: '所属公司不能为空',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 10,
            message: '在1-10字符之间',
            trigger: ['blur', 'change']
          }
        ],
        province: [
          {
            required: true,
            message: '城市不能为空',
            trigger: ['blur']
          }
        ],
        tags: [
          {
            required: true,
            message: '标签不能为空',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 10,
            message: '在1-10字符之间',
            trigger: ['blur', 'change']
          }
        ],
        remarks: [
          {
            required: true,
            message: '备注不能为空',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 50,
            message: '在1-50字符之间',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.dataform.id ? '编辑用户' : '创建用户'
    }
  },

  // 标题
  watch: {
    // 侦听省的变化拿到选定省的id（val)
    sheng: {
      handler: async function (val) {
        // 这里必须进行判断，因为是侦听，点左侧树状图的时候值也会变，也就会走这里
        // 清空并发起请求，必须根据编辑按判断一下，如果是禁用状态，就不做清
        // 空和发起请求，正常通过树状图请求数据，如果是非禁用状态，就走下面的步骤
        if (!this.isdisabled) {
          // val: 每一项的id
          // 这里做清空是因为省的变化了要清空后面的两个
          this.shiList = []
          this.shi = ''
          // console.log(this.shiList)
          this.shiList = await this.getSiteFn(val)
        }
      }
    }
  },
  created() {
    this.getBusAdmin()
    this.province()
  },
  methods: {
    // 城市
    province() {
      ChineseDistricts.forEach((item) => {
        item.cityList.forEach((item1) => {
          this.provinceArry.push(item1)
        })
      })
    },
    // 地区
    provinceFn(xx) {
      this.form.city = ''
      this.dataform.city = ''
      this.provinceArry.forEach((item) => {
        if (item.code === xx) {
          this.cityArry = item.areaList
        }
      })
    },
    // 请求企业管理列表
    async getBusAdmin() {
      const res = await getBusAdminApi(this.page, this.pagesize)
      this.tableData = res.data.items
      this.total = res.data.counts
    },
    // 顶部表单清除
    clearFn() {
      this.form = {
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: ''
      }
      this.cityArry = []
    },
    // 顶部表单搜索
    async onSubmit() {
      if (this.form.state === '') {
        this.getBusAdmin()
        return
      }
      const res = await getFirmApi(this.form)
      this.tableData = res.data.items
      this.total = res.data.counts
    },
    // 序号
    indexFn(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 状态
    formatterFn(row, column, cellValue) {
      if (cellValue === 1 || cellValue === '1') {
        return '可用'
      } else if (cellValue === 0 || cellValue === '0') {
        return '停用'
      }
      return cellValue
    },
    // 新增用户
    addUserFn() {
      this.dialogVisible = true
    },
    // 编辑
    async editFn(id) {
      this.id = id
      const res = await getBusAdminDetailsApi(id)
      this.dialogVisible = true
      this.dataform = res.data
    },
    // 禁用启用
    async forbiddenFn(id, i) {
      if (i === 0) {
        this.$confirm('确定要禁用吗？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            await editStateApi(id, i)
            this.$message.success('禁用成功')
            this.getBusAdmin()
          })
          .catch(() => {
            console.log('取消成功')
          })
      } else if (i === 1) {
        this.$confirm('确定要启用吗？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            await editStateApi(id, i)
            this.$message.success('启用成功')
            this.getBusAdmin()
          })
          .catch(() => {
            console.log('取消成功')
          })
      }
    },
    // 删除
    async delFn(id) {
      this.$confirm('此操作将永久删除用户 , 是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delUserApi(id)
          this.$message.success('删除成功')
          this.getBusAdmin()
        })
        .catch(() => {
          console.log('点击了取消')
        })
    },
    // 弹窗内的取消
    cancel() {
      this.dialogVisible = false
      this.dataform = {
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: ''
      }
      this.cityArry = []
      this.$refs.dataform.resetFields()
    },
    // 弹窗内确定按钮
    async subeditFn() {
      if (this.dataform.id) {
        // 走编辑
        if (this.dataform.isFamous === 1) {
          this.dataform.isFamous = true
        } else if (this.dataform.isFamous === 0) {
          this.dataform.isFamous = false
        }
        await editBusAdminApi(this.dataform.id, this.dataform)
        this.$message.success('修改成功')
      } else {
        // 走添加
        await addBusAdminApi(this.dataform)
        this.$message.success('添加成功')
      }
      this.cancel()
      this.getBusAdmin()
    },
    //
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.getBusAdmin()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getBusAdmin()
      // console.log(`当前页: ${val}`)
    }
  }
}
</script>
<style scoped lang="scss">
.box {
  background-color: #f0f2f5;
  overflow: hidden;
}
.body {
  background-color: #fff;
  margin: 0 20px;
  padding: 0 20px;
}
// 表单
.el-form {
  margin: 44px 0px 0 0px;
  background-color: rgb(255, 255, 255);
  width: 100%;
  height: 160px;
  padding-top: 20px;
}
.el-form-item {
  float: left;
}
.formone {
  .el-input {
    width: 220px;
  }
}
.el-select {
  width: 220px;
}
// 列表
.el-table--enable-row-transition {
  margin: 0 10px 0 10px;
  width: 98% !important;
  padding: 20px 20px;
}
// 分页
.el-pagination {
  margin-bottom: 140px;
  height: 60px;
  padding-top: 20px;
  width: 100%;
  padding-left: 760px;
  background-color: #fff;
}
// 新增用户按钮
.el-button--success {
  position: absolute;
  right: 60px;
  top: 180px;
}
// 弹窗
::v-deep {
  .el-dialog {
    border-radius: 10px;
  }
}
::v-deep {
  .el-dialog__header {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-color: #409eff;
  }
}
.el-input {
  width: 460px;
}
.el-select {
  margin-right: 10px;
}
.el-textarea {
  width: 460px;
}
// 注释
.annotation {
  margin-top: 130px;
  width: 100%;
  text-align: center;
  padding-bottom: 30px;
}
// 按钮
::v-deep {
  .el-dialog__footer {
    text-align: center;
  }
}
.popform {
  height: 400px;
  margin: 0;
}
</style>
